import json
import talib

import numpy as np
import os

import baostock as bs
import pandas as pd

# Create your views here.
from django.db.models import Count
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from yaml import serialize

from chartstest.datasViews import connectushare
from chartstest.models import TusharDate, DealDetail, stock_basic, history_k_data
import tushare as ts


def downdataIndex(request):
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)
    # tscode 分组
    result = TusharDate.objects.values('tscode').annotate(Count=Count('tscode')).order_by('-id')[:3]
    # print(type(result))
    # print(result.count())

    for obj in result:
        # print(obj)
        data_list.append(obj)

    # for i in range(0, len(book_list)):
    #     #data_list.append(book_list[i][9])
    #     print(i)
    # print(book_list.count())

    # print("json:" + json.dumps(data_list))
    # print(data_list)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'baostock/downdataIndex.html', {"dataList": json.dumps(data_list, ensure_ascii=False)})


# 在处理函数加此装饰器即可
@csrf_exempt
def downstockIndex(request):
    # 从tushare查询某只股票日线数据
    # pro = connectushare
    # 查询当前所有正常上市交易的股票列表
    pro = ts.pro_api('09c23ca7df4d6e0692459fd98de6207c1d687158fb1e946f5be77af8')

    data = pro.query('stock_basic', exchange='', list_status='L',
                     fields='ts_code,symbol,name,area,industry,market,exchange,list_status,list_date,delist_date,is_hs')
    pd.set_option('display.max_columns', None)
    # if data is None:
    #     return info
    # 排序
    print("排序------------")
    # print(data)
    # 将date值转换为datetime类型，并且设置成index
    data.index = data.ts_code

    # dataform 转成list
    train_data = np.array(data)  # np.ndarray()
    train_x_list = train_data.tolist()  # list

    # 数据排序，正序
    train_x_list.sort(key=lambda x: x[0], reverse=True)

    for i in range(1, len(train_x_list)):
        print("股票代码:" + train_x_list[i][0])
        print("股票名称:" + train_x_list[i][1])
        s = stock_basic()
        s.code = train_x_list[i][0]
        s.symbol = train_x_list[i][1]
        s.name = train_x_list[i][2]
        s.area = train_x_list[i][3]
        s.industry = train_x_list[i][4]
        # s.fullname = train_x_list[i][0]
        # s.enname = train_x_list[i][0]
        s.market = train_x_list[i][5]
        s.exchange = train_x_list[i][6]
        # s.curr_type = train_x_list[i][0]
        s.list_status = train_x_list[i][7]
        s.list_date = train_x_list[i][8]
        s.delist_date = train_x_list[i][9]
        s.is_hs = train_x_list[i][10]
        s.save()

    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")


# 在处理函数加此装饰器即可
@csrf_exempt
def jsonDate(request):
    tscode = request.POST['tscode']
    tusharDates = TusharDate.objects.filter(tscode=tscode)
    # print(tusharDates)

    # ret = models.TusharDate.objects.all().order_by("dayIncome", "id")
    ret1 = serialize("json", tusharDates)
    retList = json.loads(ret1)
    # print(retList)
    ret2 = []
    print('---------------------')
    for num in range(len(retList)):
        fields = retList[num]['fields']
        fields.update(id=retList[num]['pk'])
        ret2.append(fields)
        # print(ret2)

    data = {'status': 0, 'dates': ret2}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")


# 计算查询结果
# 在处理函数加此装饰器即可
@csrf_exempt
def downdataResult(request):
    tscode = request.POST['tscode']
    startTime = request.POST['startTime']
    endTime = request.POST['endTime']
    #
    ls = json.dumps(tscode, ensure_ascii=False)
    info = HttpResponse(ls)

    # 下面这两行设置夸域请求，跨域就是用这两行
    # info['Access-Control-Allow-Origin'] = '*'
    # info['Access-Control-Allow-Headers'] = "Content-Type"
    if tscode == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    if startTime == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    if endTime == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    startTime = startTime.replace('-', '')
    endTime = endTime.replace('-', '')
    ts_code = '600575.SH'
    start_date = '20180701'
    end_date = '20191024'
    #### 登陆系统 ####
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    # date  交易所行情日期
    # code 证券代码
    # open 开盘价
    # high 最高价
    # low 最低价
    # close 收盘价
    # preclose 前收盘价
    # volume 成交量（累计 单位：股）
    # amount 成交额（单位：人民币元）
    # adjustflag 复权状态(1：后复权， 2：前复权，3：不复权）
    # turn 换手率 [指定交易日的成交量(股 ) /指定交易日的股票的流通股总股数(股) ] *10 0%       tradestatus 	交易状态(1：正常交易 0：停牌）
    # pctChg 	涨跌幅（百分比） 	日涨跌 幅 =[(指定交易日的收盘 价 -指定交易日前收盘价 ) /指定交易日前收盘价 ] *10 0%
    #                            peTTM 	滚动市盈率 	(指定交易日的股票收盘 价 /指定交易日的每股盈余TTM ) =(指定交易日的股票收盘 价 *截至当日公司总股本 ) /归属母公司股东净利润TTM
    # pbMRQ 	市净率 	(指定交易日的股票收盘 价 /指定交易日的每股净资产 ) =总市 值 /(最近披露的归属母公司股东的权 益 -其他权益工具)
    # psTTM 	滚动市销率 	(指定交易日的股票收盘 价 /指定交易日的每股销售额 ) =(指定交易日的股票收盘 价 *截至当日公司总股本 ) /营业总收入TTM
    # pcfNcfTTM 	滚动市现率 	(指定交易日的股票收盘 价 /指定交易日的每股现金流TTM ) =(指定交易日的股票收盘 价 *截至当日公司总股本 ) /现金以及现金等价物净增加额TTM
    # isST 	是否ST股，1是，0否

    #### 获取历史K线数据 ####
    # 详细指标参数，参见“历史行情指标参数”章节
    rs = bs.query_history_k_data_plus(tscode,
                                      "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
                                      start_date=startTime, end_date=endTime,
                                      frequency="d", adjustflag="3")  # frequency="d"取日k线，adjustflag="3"默认不复权
    print('query_history_k_data_plus respond error_code:' + rs.error_code)
    print('query_history_k_data_plus respond  error_msg:' + rs.error_msg)
    pd.set_option('display.max_columns', None)

    data = rs.data
    # dataform 转成list
    train_data = np.array(data)  # np.ndarray()
    train_x_list = train_data.tolist()  # list
    #### 打印结果集 ####

    for i in range(1, len(train_x_list)):
        print("数据开始---------------")
        print(train_x_list[i][1])
        h = history_k_data()
        h.code = train_x_list[i][1]
        h.date = train_x_list[i][1]
        h.open = train_x_list[i][1]
        h.high = train_x_list[i][1]
        h.low = train_x_list[i][1]
        h.close = train_x_list[i][1]
        h.preclose = train_x_list[i][1]
        h.volume = train_x_list[i][1]
        h.amount = train_x_list[i][1]
        h.adjustflag = train_x_list[i][1]
        h.turn = train_x_list[i][1]
        h.tradestatus = train_x_list[i][1]
        h.pctChg = train_x_list[i][1]
        h.peTTM = train_x_list[i][1]
        h.psTTM = train_x_list[i][1]
        h.pcfNcfTTM = train_x_list[i][1]


    return info


# 详细信息
@csrf_exempt
def downdataDetail(request):
    print("--------------------------------------详细信息")
    # 参数
    id = request.GET['id']
    data_list = []
    result = DealDetail.objects.filter(tusharDate_id=id)

    ret1 = serialize("json", result)
    retList = json.loads(ret1)
    # print(retList)

    for num in range(len(retList)):
        fields = retList[num]['fields']

        fields.update(id=retList[num]['pk'])
        data_list.append(fields)
        # print(ret2)

    tusharDate_id = data_list[0]['tusharDate']

    # print("tscode:" + json.dumps(tscode))

    # 读取文件数据
    data = pd.read_csv(str(tusharDate_id) + '.csv')
    train_data = np.array(data)  # np.ndarray()
    macdlist = train_data.tolist()  # list
    macdlist.sort()
    # print(macdlist)
    # print(type(macdlist))

    # ret1 = serialize("json", datelist)
    # retList = json.loads(ret1)
    # # print(retList)
    # ret2 = []
    # print('---------------------')
    # for num in range(len(retList)):
    #     print(retList[num])
    #
    #     ret2.append(fields)
    #     # print(ret2)

    aaaalist = json.dumps(macdlist, ensure_ascii=False)
    # print(aaaalist)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'chartstest/macdDetails.html', {"detailList": json.dumps(data_list, ensure_ascii=False),
                                                           "macdlist": aaaalist})


# 在处理函数加此装饰器即可
@csrf_exempt
def delDate(request):
    tscode = request.POST['tscode']

    tusharDates = TusharDate.objects.filter(tscode=tscode)
    # print(tusharDates)

    for obj in tusharDates:
        url = str(obj.id) + ".csv"
        if os.path.isfile(url):
            os.remove(url)
        print(obj.id)

    DealDetail.objects.filter(tscode=tscode).delete()

    TusharDate.objects.filter(tscode=tscode).delete()
    # ret = models.TusharDate.objects.all().order_by("dayIncome", "id")

    data = {'status': 0, 'message': '删除成功！'}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")
